<?php

declare(strict_types=1);

namespace app\common\command;

use app\admin\model\IndexRule;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\App;

class ImportSystemRule extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('import:system_rule')
            ->setDescription('the import:system_rule command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('import:system_rule');

        $file_path = App::getRootPath() . '/source/system_rule_blocking.txt';

        $this->readFile($file_path,'@@');

        $file_path = App::getRootPath() . '/source/system_rule.txt';

        $this->readFile($file_path, '');
    }

    public function readFile($file_path, $rule_prefix = '')
    {
        $file = fopen($file_path, "r") or exit("Unable to open file!");
        //Output a line of the file until the end is reached
        //feof() check if file read end EOF
        while (!feof($file)) {
            //fgets() Read row by row
            $content = fgets($file);

            $this->saveContent($content, $rule_prefix);
        }
        fclose($file);
    }

    public function saveContent($content, $rule_prefix = '')
    {

        if ($content === false) {
            return;
        }

        $content = trim($content);

        // 判断是不是空行
        if (empty($content)) {
            return;
        }
        $content = trim($content, ',');
        $content = trim($content, '"');

        $content = $rule_prefix . '||' . $content . '^';

        $model_rule = IndexRule::where('content', $content)->where('user_id', 0)->find();

        if (empty($model_rule)) {
            $model_rule = new IndexRule();

            $model_rule->content = $content;
            $model_rule->status = 'enable';
            $model_rule->user_id = 0;
            $model_rule->public_status = 'apply';
            $model_rule->save();
            $this->output->writeln('new rule:' . $content);
        }
    }
}
